package renguanyu.app.auth4fx.controller.user;

import javafx.concurrent.Task;
import javafx.scene.control.CheckBox;
import renguanyu.app.auth4fx.model.user.UserRoleDto;
import renguanyu.app.auth4fx.service.user.UserRoleService;
import renguanyu.app.auth4fx.view.user.UserListView;
import renguanyu.app.auth4fx.view.user.UserRoleListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserRoleListQueryController extends Task<Void> {

    private UserRoleListView userRoleListView;
    public UserRoleListQueryController(UserRoleListView userRoleListView){
        this.userRoleListView = userRoleListView;
    }

    public UserRoleListQueryController(){
    }

    public void execute() {
        System.out.println("UserRoleListQueryController.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private List<Map<String, Object>> mapList1 = new ArrayList<>();
    private List<Map<String, Object>> mapList2 = new ArrayList<>();
    private Integer totalPages = 0;
    @Override
    protected Void call() {
        System.out.println("UserRoleListQueryController.call");
        UserRoleDto userRoleDto = buildUserRoleDto();
        mapList1 = UserRoleService.queryUnownedRoleList(userRoleDto);
        mapList2 = UserRoleService.queryOwnedRoleList(userRoleDto);
        return null;
    }

    private static UserRoleDto buildUserRoleDto() {
        String userId = UserListView.selectedUser.getId();
        UserRoleDto userRoleDto = new UserRoleDto();
        userRoleDto.setUserId(userId);
        return userRoleDto;
    }


    @Override
    protected void running() {
        System.out.println("UserRoleListQueryController.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("UserRoleListQueryController.succeeded");

        List<CheckBox> checkBoxList = mapList1.stream().map(e -> {
            String id = e.get("id").toString();
            String name = e.get("name").toString();
            CheckBox checkBox = new CheckBox(name);
            checkBox.getProperties().put("id", id);
            checkBox.getProperties().put("name",name);
            return checkBox;
        }).toList();
        userRoleListView.leftCheckBoxContainer.getChildren().addAll(checkBoxList);

        List<CheckBox> checkBoxList2 = mapList2.stream().map(e -> {
            String id = e.get("id").toString();
            String roleName = e.get("role_name").toString();
            CheckBox checkBox = new CheckBox(roleName);
            checkBox.getProperties().put("id", id);
            checkBox.getProperties().put("name",roleName);
            return checkBox;
        }).toList();
        userRoleListView.rightCheckBoxContainer.getChildren().addAll(checkBoxList2);

    }

    @Override
    protected void failed() {
        System.out.println("UserRoleListQuery.failed");
    }

}
